package withdraw

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type WithdrawFindLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// c端用户提现页面--提现订单历史记录
func NewWithdrawFindLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WithdrawFindLogic {
	return &WithdrawFindLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WithdrawFindLogic) WithdrawFind(req *types.WithdrawListPageReq) (resp *types.WithdrawListPageRes, err error) {
	UserId := headInfo.GetTokenUid(l.ctx)
	if UserId == 0 {
		return nil, xerrors.UserTokenInvalid
	}
	rpc_req := &rpc.UserFindWithDrawReq{
		UserId:  UserId,
		Status:  req.Status,
		Channel: req.TypeId,
		TmStart: req.StartTime,
		TmEnd:   req.EndTime,
		Page: &rpc.Page{
			Page:     req.Page,
			PageSize: req.PageSize,
		},
	}

	// 发送请求
	rpc_resp, err := l.svcCtx.AssetsRpc.PayWithdraw.WithdrawUserListPage(l.ctx, rpc_req)
	if err != nil {
		logx.Errorf("Call ModifyVipLevelInfos error: %v", err)
		return nil, err
	}

	// 处理请求返回的结果
	// 解析、组合数据
	resp = &types.WithdrawListPageRes{
		Data:     make([]types.WithdrawListPageRes_Data, 0),
		Page:     req.Page,
		PageSize: req.PageSize,
		Total:    rpc_resp.Page.Total,
	}
	for _, d := range rpc_resp.Data {
		if d.Status == int32(rpc.WithDrawStatus_UnLock) {
			d.Status = int32(rpc.WithDrawStatus_Pass)
		}
		if d.Status == int32(rpc.WithDrawStatus_Lock) {
			d.Status = int32(rpc.WithDrawStatus_Pass)
		}
		if d.Status == int32(rpc.WithDrawStatus_Fail) {
			d.Status = int32(rpc.WithDrawStatus_Refuse)
		}
		resp.Data = append(resp.Data, types.WithdrawListPageRes_Data{
			Id:          int64(d.ID),
			Amount:      d.OrderAmount,
			OrderNo:     d.OrderNo,
			CreatedAt:   d.CreatedAt,
			ChannelType: d.ChannelType,
			Status:      int64(d.Status),
			Remark:      d.LockerRemark,
		})
	}
	return
}
